package com.android.example.app3;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class RuleFileManager {
    private static final String TAG = "RuleFileManager";
    private final Context context;

    public RuleFileManager(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("Context cannot be null");
        }
        this.context = context.getApplicationContext();
    }

    /**
     * 添加规则到指定文件
     *
     * @param name 规则名称
     * @param list 文件列表名称（不含扩展名）
     */
    public void addRuleToFile(String name, String list) {
        File externalFilesDir = context.getExternalFilesDir(null);
        if (externalFilesDir == null) {
            Log.e(TAG, "addRuleToFile: External storage directory is not available.");
            return;
        }

        File rulesFile = new File(externalFilesDir, list + ".txt");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(rulesFile, true))) {
            writer.write(name);
            writer.newLine();
            writer.flush();
        } catch (IOException e) {
            Log.e(TAG, "addRuleToFile: ", e);
        }
    }

    /**
     * 在WebView中显示指定规则文件的内容
     *
     * @param webView  要显示内容的WebView组件
     * @param listName 文件列表名称（不含扩展名）
     */
    public void displayRulesFileInWebView(WebView webView, String listName) {
        File externalFilesDir = context.getExternalFilesDir(null);
        if (externalFilesDir == null) {
            Log.e(TAG, "displayRulesFile: External storage directory not available");
            webView.loadData("<h3>Error: Storage unavailable</h3>", "text/html", "UTF-8");
            return;
        }

        File rulesFile = new File(externalFilesDir, listName + ".txt");

        if (!rulesFile.exists()) {
            webView.loadData("<h3>File not found: " + rulesFile.getName() + "</h3>", "text/html", "UTF-8");
            return;
        }

        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(rulesFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(TextUtils.htmlEncode(line)).append("<br>");
            }
        } catch (IOException e) {
            Log.e(TAG, "Error reading file", e);
            webView.loadData("<h3>Error reading file</h3><p>" + "body {" +
                    "   margin: 0;" +
                    "   padding: 20px;" +
                    "   background: transparent;" +
                    "   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;" +
                    "   -webkit-user-select: text; /* Allow text selection */" +
                    "   user-select: text;" +
                    "}" + e.getMessage() + "</p>", "text/html", "UTF-8");
            return;
        }

        String htmlContent = "<!DOCTYPE html><html><head>" +
                "<meta charset=\"UTF-8\">" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" +
                "<style>body { font-family: sans-serif; line-height: 1.6; padding: 16px; }</style>" +
                "</head><body>" +
                contentBuilder.toString() +
                "</body></html>";

        webView.loadDataWithBaseURL(null, htmlContent, "text/html", "UTF-8", null);
    }
}